package cn.smile.controller;

import cn.smile.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: MaoSuyu
 * @User：John
 * @Date: 2019/7/2
 * @Time: 15:56
 * @Description: No Description
 */
@RestController
public class TestController {


    /**
     * 登录
     *
     * @return
     */
    @RequestMapping("/login")
    public String login() {
        return "登录";
    }


    /**
     * 登录成功后该方法不再运行
     *
     * @param request
     * @param user
     * @return
     */
    @RequestMapping("/login.do")
    public String login(HttpServletRequest request, User user) {
        System.out.println("登录");
        //用户凭证
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getUserPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            //执行登录操作
            subject.login(token);
        } catch (UnknownAccountException e) {
            return "用户不存在";
        } catch (IncorrectCredentialsException e) {
            return "密码错误";
        } catch (ExpiredCredentialsException e) {
            return "凭证过期";
        } catch (Exception e) {
            return "未知的错误";
        }
        return "登录成功";
    }

    /**
     * 主页
     *
     * @return
     * @RequiresPermissions("index") 该注解用于配置权限
     */
    @RequestMapping("/index")
    public String index() {
        final User user = (User)SecurityUtils.getSubject().getPrincipal();
        System.out.println("主页");
        return "欢迎"+user.getUserName()+ "来到主页";
    }

}
